package liuwanghui.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import liuwanghui.dto.request.UserQueryDTO;
import liuwanghui.dto.request.UserUpdateDTO;
import liuwanghui.dto.response.DashboardStatisticsDTO;
import liuwanghui.exception.BusinessException;
import liuwanghui.mapper.AdminMapper;
import liuwanghui.pojo.Result;
import liuwanghui.service.AdminService;
import liuwanghui.util.CacheUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Slf4j
@Service
@RequiredArgsConstructor
public class AdminServiceImpl implements AdminService {

    private final AdminMapper adminMapper;
    private final CacheUtil cacheUtil;

    @Override
    public Result getUserList(UserQueryDTO params) {
        PageHelper.startPage(params.getPage(), params.getPageSize());
        var users = adminMapper.findUsersBySearch(params);
        return Result.success(new PageInfo<>(users));
    }

    @Override
    public Result getUserDetail(Long id) {
        return Result.success(adminMapper.findUserById(id));
    }

    @Override
    @Transactional
    public void updateUser(Long id, UserUpdateDTO dto) {
        adminMapper.updateUser(id, dto);
    }

    @Override
    @Transactional
    public void updateUserStatus(Long id, String status) {
        adminMapper.updateUserStatus(id, status);
    }

    @Override
    public Result getDashboardStatistics() {
        DashboardStatisticsDTO stats = new DashboardStatisticsDTO();
        
        // 用户统计
        stats.setUserCount(adminMapper.getUserCount());
        
        // 订单统计
        stats.setOrderCount(adminMapper.getOrderCount());
        
        // 商品统计
        stats.setProductCount(adminMapper.getProductCount());
        
        // 交易额统计
        stats.setTradingAmount(adminMapper.getTradingAmount());
        
        return Result.success(stats);
    }

    @Override
    @Transactional
    public Result resetUserPassword(Long userId, String newPassword) {
        try {
            adminMapper.resetUserPassword(userId, newPassword);
            return Result.success();
        } catch (Exception e) {
            log.error("重置用户密码失败", e);
            throw new BusinessException("重置用户密码失败");
        }
    }
} 